package com.comsoftstar.nt5s.Activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hzc.imagepicker.SImagePicker;
import com.hzc.imagepicker.activity.PhotoPickerActivity;
import com.hzc.nt5s.IConstant;
import com.hzc.nt5s.R;
import com.hzc.nt5s.adapter.GridViewAdapter;
import com.hzc.nt5s.adapter.PickAdapter;
import com.hzc.nt5s.deviceManager.bean.User;
import com.hzc.nt5s.deviceManager.preference.PreferencesUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.KeyValue;
import org.xutils.http.RequestParams;
import org.xutils.http.body.MultipartBody;
import org.xutils.x;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class DetailActivity extends AppCompatActivity implements View.OnClickListener {

    public static final int REQUEST_CODE_IMAGE = 101;
    private TextView tv_group, tv_outdate, tv_regulation, tv_newcardnum,
            tv_person, tv_checkdate, tv_isYN, tv_note, tv_change, tv_changeperson,
            tv_seccheckresult, tv_seccheckdate, tv_changedate, tv_description;
    private EditText et_change, et_changeperson;
    private GridView gridView, secgrid, standardgrid;
    private GridViewAdapter gridViewadapter, gridViewadapter2, gridViewadapter3;
    private PickAdapter pickAdapter;
    private Button btn_back, btn_save, btn_upload;
    private LinearLayout ll_change, ll_seccheck, ll_changepic;
    private JSONObject jo, jo_standard, jo_change;
    private JSONArray ja_standard, ja_change;
    private Calendar calendar;
    private List<String> url = new ArrayList<>();
    private List<String> changeurl = new ArrayList<>();
    private List<String> standardurl = new ArrayList<>();
    private List<String> pickedlist = new ArrayList<>();
    private boolean isShowDelete = false;
    private View line_ll_seccheck, line_changedate, line_btn_upimage, line_changepic;
    private boolean ischangedetail=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        initView();
        initData();
        addview();
        addeditchange();
    }

    private void initData() {
        Intent intent = getIntent();
        String s = intent.getStringExtra("detail");
        System.out.println(s);
        try {
            jo = new JSONObject(s);
            System.out.println("Json:" + jo);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new Thread() {
            public void run() {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    // Auto-generated catch block
                    e.printStackTrace();
                }
                getStandardPic();
            }
        }.start();


    }

    private void getStandardPic() {
        RequestParams params = new RequestParams(IConstant.URL + "getStandardPic");
        params.addBodyParameter("Guid", jo.optString("Guid"));
//        System.out.println("请求的URL：" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
//                System.out.println("返回结果：" + result);
                if (!result.equals("[]")) {
                    try {
                        ja_standard = new JSONArray(result);
                        if (ja_standard != null && ja_standard.length() > 0) {
                            standardurl.clear();
                            List<String> standard_url = new ArrayList<>();
                            for (int i = 0; i < ja_standard.length(); i++) {
                                jo_standard = (JSONObject) ja_standard.get(i);
                                standard_url.add(jo_standard.optString("Rative_Path"));
                            }
                            for (int i = 0; i < standard_url.size(); i++) {
                                standardurl.add(IConstant.URL_IMG + standard_url.get(i));
                            }
                            gridViewadapter2 = new GridViewAdapter(DetailActivity.this, standardurl);
                            standardgrid.setAdapter(gridViewadapter2);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    private void initView() {

        pickAdapter = new PickAdapter(this);
        calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        btn_back = (Button) findViewById(R.id.tv_back_detail);
        btn_back.setOnClickListener(this);
        btn_save = (Button) findViewById(R.id.tv_save_detail);
        btn_save.setOnClickListener(this);
        gridView = (GridView) findViewById(R.id.view_check_pic);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                seeBig(url, i);
            }
        });
        secgrid = (GridView) findViewById(R.id.view_change_pic);
        secgrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                seeBig(changeurl, i);
            }
        });

        standardgrid = (GridView) findViewById(R.id.view_standard_pic);
        standardgrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                seeBig(standardurl, i);
            }
        });
        tv_regulation = (TextView) findViewById(R.id.detail_regulation);
        tv_group = (TextView) findViewById(R.id.detail_workshop);
        tv_checkdate = (TextView) findViewById(R.id.detail_checkdate);
        tv_person = (TextView) findViewById(R.id.detail_person);
        tv_newcardnum = (TextView) findViewById(R.id.detail_newcardnum);
        tv_isYN = (TextView) findViewById(R.id.detail_isYN);
        tv_description = (TextView) findViewById(R.id.detail_description);
        tv_note = (TextView) findViewById(R.id.detail_note);
        tv_outdate = (TextView) findViewById(R.id.detail_outdate);
        tv_changeperson = (TextView) findViewById(R.id.tv_detail_changeperson);
        et_changeperson = (EditText) findViewById(R.id.et_detail_changeperson);
        tv_change = (TextView) findViewById(R.id.detail_change_tv);
        et_change = (EditText) findViewById(R.id.detail_change_et);
        tv_changedate = (TextView) findViewById(R.id.detail_changedate);
        btn_upload = (Button) findViewById(R.id.btn_upimage);
        btn_upload.setOnClickListener(this);
        ll_change = (LinearLayout) findViewById(R.id.ll_changedate);
        ll_seccheck = (LinearLayout) findViewById(R.id.ll_seccheck);
        ll_changepic = (LinearLayout) findViewById(R.id.ll_change_pic);
        tv_seccheckdate = (TextView) findViewById(R.id.detail_seccheckdate);
        tv_seccheckresult = (TextView) findViewById(R.id.detail_seccheckresult);
        line_btn_upimage = findViewById(R.id.line_btn_upimage);
        line_changedate = findViewById(R.id.line_changedate);
        line_changepic = findViewById(R.id.line_changepic);
        line_ll_seccheck = findViewById(R.id.line_ll_seccheck);
    }

    private void delete(int position) {//删除选中项方法
        List<String> newList = new ArrayList<String>();
        if (isShowDelete) {
            pickedlist.remove(position);
        }
        newList.addAll(pickedlist);
        pickedlist.clear();
        pickedlist.addAll(newList);
        changeurl.clear();
        changeurl.addAll(newList);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_back_detail:
                if (jo.optString("ISOK").equals("0")) {
                    if (!(TextUtils.isEmpty(et_changeperson.getText())) || !(TextUtils.isEmpty(et_change.getText())) || (pickedlist != null && !pickedlist.isEmpty())) {
                        if (ischangedetail)
                        BackToSearch();
                        else
                            finish();
                    } else {
                        finish();
                    }
                } else {
                    finish();
                }
                break;
            case R.id.btn_upimage:
                SImagePicker
                        .from(DetailActivity.this)
                        .maxCount(9)
                        .rowCount(3)
                        .showCamera(true)
                        .pickMode(SImagePicker.MODE_IMAGE)
                        .forResult(REQUEST_CODE_IMAGE);
                break;
            case R.id.tv_save_detail:
                User user = PreferencesUtil.getUser(DetailActivity.this);
                String name = user.getName();
                System.out.println("name:" + name);
                if (name.equals(jo.optString("Director")) || name.equals(jo.optString("PosLeader")) || name.equals(jo.optString("DeputyLeader")) || name.equals("系统管理员")|| name.equals(jo.optString("groupName"))) {
                    if (TextUtils.isEmpty(et_changeperson.getText())) {
                        Toast.makeText(DetailActivity.this, "请输入责任人", Toast.LENGTH_LONG).show();
                    } else if (TextUtils.isEmpty(et_change.getText())) {
                        Toast.makeText(DetailActivity.this, "请输入改善措施", Toast.LENGTH_LONG).show();
                    } else {
                            SaveDialog();
                    }
                } else {
                    Toast.makeText(DetailActivity.this, "没有修改权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }
    private void addeditchange(){
        et_changeperson.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                ischangedetail=true;
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        et_change.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                ischangedetail=true;
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void addview() {

        url.clear();
        String img_url[] = jo.optString("ImagePath").split(",");
        for (int i = 0; i < img_url.length; i++) {
            url.add(IConstant.URL_IMG + img_url[i]);
        }
        gridViewadapter = new GridViewAdapter(DetailActivity.this, url);
        gridView.setAdapter(gridViewadapter);
        tv_regulation.setText(jo.optString("Regulation"));
        tv_group.setText(jo.optString("groupName"));
        tv_checkdate.setText(jo.optString("CheckDate").split(" ")[0]);
        tv_person.setText(jo.optString("Person"));
        tv_newcardnum.setText(jo.optString("NewCardNum"));
        tv_isYN.setText(jo.optString("isYN"));
        tv_description.setText(jo.optString("Description"));
        tv_note.setText(jo.optString("Note"));
        tv_outdate.setText(jo.optString("OutDate").split(" ")[0]);


//        if (jo.optString("ChangeDate").equals("")) {
//            ll_changepic.setVisibility(View.GONE);
//            ll_change.setVisibility(View.GONE);
//            line_changepic.setVisibility(View.GONE);
//            line_changedate.setVisibility(View.GONE);
//            btn_upload.setVisibility(View.VISIBLE);
//            line_btn_upimage.setVisibility(View.VISIBLE);
//        } else {
//            ll_changepic.setVisibility(View.VISIBLE);
//            new Thread() {
//                public void run() {
//                    try {
//                        Thread.sleep(500);
//                    } catch (InterruptedException e) {
//                        // Auto-generated catch block
//                        e.printStackTrace();
//                    }
//                    getChangePic();
//                }
//            }.start();
//            tv_changedate.setText(jo.optString("ChangeDate").split(" ")[0]);
//
//        }
        if (jo.optString("ISOK").equals("0")) {
            btn_upload.setVisibility(View.VISIBLE);
            line_btn_upimage.setVisibility(View.VISIBLE);
            btn_save.setClickable(true);

            if (jo.optString("Change").equals("")) {
                tv_change.setVisibility(View.GONE);
                et_change.setVisibility(View.VISIBLE);
            } else {
                tv_change.setVisibility(View.GONE);
                et_change.setVisibility(View.VISIBLE);
                et_change.setText(jo.optString("Change"));
            }
            et_changeperson.setText(jo.optString("ChangePerson"));
            ll_changepic.setVisibility(View.VISIBLE);
            new Thread() {
                public void run() {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        // Auto-generated catch block
                        e.printStackTrace();
                    }
                    getChangePic();
                }
            }.start();
            tv_changedate.setText(jo.optString("ChangeDate").split(" ")[0]);

        } else {
            btn_save.setClickable(false);
            tv_change.setText(jo.optString("Change"));
            tv_changeperson.setVisibility(View.VISIBLE);
            et_changeperson.setVisibility(View.GONE);
            tv_changeperson.setText(jo.optString("ChangePerson"));
            et_changeperson.setText(jo.optString("ChangePerson"));
            et_changeperson.setFocusable(false);
            et_changeperson.setFocusableInTouchMode(false);
            ll_changepic.setVisibility(View.VISIBLE);
            new Thread() {
                public void run() {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        // Auto-generated catch block
                        e.printStackTrace();
                    }
                    getChangePic();
                }
            }.start();
            tv_changedate.setText(jo.optString("ChangeDate").split(" ")[0]);
        }

        if (jo.optString("SecCheckResult").equals("")) {
            ll_seccheck.setVisibility(View.GONE);
            line_ll_seccheck.setVisibility(View.GONE);
        } else {
            tv_seccheckdate.setText(jo.optString("SecCheckDate").split(" ")[0]);
            tv_seccheckresult.setText(jo.optString("SecCheckResult"));
        }


    }

    private void getChangePic() {
        RequestParams params = new RequestParams(IConstant.URL + "getChangePic");
        params.addBodyParameter("Inner_No2", jo.optString("Inner_No2"));
//        System.out.println("请求的URL：" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
//                System.out.println("返回结果：" + result);
                try {
                    ja_change = new JSONArray(result);
                    if (ja_change != null && ja_change.length() > 0) {
                        changeurl.clear();
                        List<String> change_url = new ArrayList<String>();
                        for (int i = 0; i < ja_change.length(); i++) {
                            jo_change = (JSONObject) ja_change.get(i);
                            change_url.add(jo_change.optString("ImagePath"));
                        }
                        for (int i = 0; i < change_url.size(); i++) {
                            changeurl.add(IConstant.URL_IMG + change_url.get(i));
                        }
                        gridViewadapter3 = new GridViewAdapter(DetailActivity.this, changeurl);
                        secgrid.setAdapter(gridViewadapter3);
                    } else {
                        ll_changepic.setVisibility(View.GONE);
                        line_changepic.setVisibility(View.GONE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void saveData() {

        try {
            jo.put("Change", et_change.getText().toString());
            jo.put("ChangePerson", et_changeperson.getText().toString());
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String date = format.format(calendar.getTime());
            jo.put("ChangeDate", date);
            RequestParams params = new RequestParams(IConstant.URL + "updateReview");
            params.addBodyParameter("Change", jo.optString("Change"));
            params.addBodyParameter("ChangePerson", jo.optString("ChangePerson"));
            params.addBodyParameter("ChangeDate", jo.optString("ChangeDate"));
            params.addBodyParameter("ISOK", jo.optString("ISOK"));
            params.addBodyParameter("Inner_No2", jo.optString("Inner_No2"));
            params.addBodyParameter("Guid", jo.optString("Guid"));
//            System.out.println("请求的URL：" + params.toString());
            x.http().post(params, new Callback.CommonCallback<String>() {


                @Override
                public void onSuccess(String result) {
//                    System.out.println("返回结果：" + result);
                    Toast.makeText(DetailActivity.this, "保存成功", Toast.LENGTH_LONG).show();
                    try {
                        jo = new JSONObject(result);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    refresh(jo);

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }

            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            final ArrayList<String> pathList =
                    data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT_SELECTION);
            System.out.println("pathList" + pathList.toString());
            pickedlist.addAll(pathList);
            changeurl.addAll(pickedlist);
            pickAdapter = new PickAdapter(DetailActivity.this);
            pickAdapter.setNewData(pickedlist);
            secgrid.setAdapter(pickAdapter);
            ll_changepic.setVisibility(View.VISIBLE);
            line_changepic.setVisibility(View.VISIBLE);
            isShowDelete = false;
            pickAdapter.setIsShowDelete(isShowDelete);
            secgrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    seeBig(changeurl, i);
                }
            });
            secgrid.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                    if (isShowDelete) {
                        isShowDelete = false;
                    } else {
                        isShowDelete = true;
                        pickAdapter.setIsShowDelete(isShowDelete);
                        secgrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view,
                                                    int position, long id) {
                                delete(position);//删除选中项
                                pickAdapter = new PickAdapter(DetailActivity.this);//重新绑定一次adapter
                                pickAdapter.setNewData(pickedlist);
                                pickAdapter.setIsShowDelete(isShowDelete);
                                secgrid.setAdapter(pickAdapter);
                            }
                        });
                    }
                    pickAdapter.setIsShowDelete(isShowDelete);//setIsShowDelete()方法用于传递isShowDelete值
                    return true;
                }
            });

        }
    }

    private void savePic(List<String> pathList) {
        RequestParams params = new RequestParams(IConstant.URL + "upload");
        User user = PreferencesUtil.getUser(DetailActivity.this);
        params.addBodyParameter("MdCode", "002005");//操作对象
        params.addBodyParameter("UserName", user.getUserName());//文件后缀名(带点)
        List<KeyValue> list = new ArrayList<>();
        for (int i = 0; i < pathList.size(); i++) {
            list.add(new KeyValue("image" + i, new File(pathList.get(i))));
            MultipartBody body = new MultipartBody(list, "UTF-8");
            params.setRequestBody(body);
        }
//        System.out.println("请求的URL：" + params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
//                System.out.println("返回结果：" + result);
                Toast.makeText(DetailActivity.this, "上传成功", Toast.LENGTH_LONG).show();

                try {
                    jo.put("Inner_No2", result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                saveData();
            }
        });
    }

    public void seeBig(List<String> url, int position) {
        Intent intent = new Intent();
        intent.setClass(DetailActivity.this, BigImgActivity.class);
        intent.putExtra("url", url.get(position).toString());
        startActivity(intent);
    }

    private void refresh(JSONObject jo) {

        Intent intent = new Intent();
        intent.setClass(DetailActivity.this, SearchActivity.class);
        intent.putExtra("detail", jo.toString());
        setResult(1,intent);
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (isShowDelete) {
            isShowDelete = false;
            pickAdapter.setIsShowDelete(isShowDelete);
        } else {
            if (jo.optString("ISOK").equals("0")) {

                if (!(TextUtils.isEmpty(et_changeperson.getText())) || !(TextUtils.isEmpty(et_change.getText())) || (pickedlist != null && !pickedlist.isEmpty())) {
                    if (ischangedetail)
                    BackToSearch();
                    else
                        finish();
                } else {
                    finish();
                }
            } else {
                finish();
            }

        }
    }

    private void BackToSearch() {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);  //先得到构造器
        builder.setTitle("提示"); //设置标题
        builder.setMessage("未保存，确定要退出？"); //设置内容
        builder.setIcon(R.mipmap.ic_launcher);//设置图标，图片id即可
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { //设置确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss(); //关闭dialog
                finish();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { //设置取消按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        //参数都设置完成了，创建并显示出来
        builder.create().show();
    }

    private void SaveDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);  //先得到构造器
        builder.setTitle("提示"); //设置标题
        builder.setMessage("确定要保存？"); //设置内容
        builder.setIcon(R.mipmap.ic_launcher);//设置图标，图片id即可
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { //设置确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss(); //关闭dialog
                if (pickedlist != null && !pickedlist.isEmpty()) {
                    savePic(pickedlist);
                } else {
                    saveData();
                }

            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { //设置取消按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        //参数都设置完成了，创建并显示出来
        builder.create().show();
    }

}
